package com.rrqs.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.rrqs.MessageEvents;
import com.rrqs.activity.adapter.CommonAdapter;
import com.rrqs.activity.adapter.OrderDeliveryHelpAdapter;
import com.rrqs.activity.adapter.OrderDeliveryItemAdapter;
import com.rrqs.activity.adapter.ViewHolders;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.DeliveryOrderData;
import com.rrqs.activity.data.OrderDeliveryData;
import com.rrqs.activity.data.QiangDanData;
import com.rrqs.frame.JsonProcessHelper;
import com.rrqs.views.CountDownTimer;
import com.rrqs.views.LazyScrollView;
import com.rrqs.views.LazyScrollView.OnScrollListener;
import com.rrqs.views.MyListView;
import com.rrqs.views.OnChanged;
import com.zadtek.xmqishi.R;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 配送中activity
 *
 * @author Administrator
 */
public class OrderpsActivity extends BaseActivity implements OnChanged, AMapLocationListener {
    private OnChanged listener;
    private MyListView deliveryList, help_deliverylist;
    private TextView ordernull;
    OrderDeliveryAdapter deliveryadapter;
    OrderDeliveryHelpAdapter helpadapter;
    private DeliveryOrderData OrderSendList = new DeliveryOrderData();
    OrderAsyncTask mOrderAsyn;
    public static Handler mHandler;
    private String emp_id = "";
    QiangDanData qiangdan;
    private LazyScrollView waterfall_scroll;
    private View mHeaderView;// 头部的控件
    private TextView pulldown_header_text; // 头部面板
    private SharedPreferences sp;
    private ArrayList<OrderDeliveryData> psorderlist;    //配送中的订单
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;
    private double buyerLat = 0, buyerLnt = 0;
    private double lat = 0, lnt = 0;
    private SparseArray<CountDownTimer> timers;
    private float distance = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        EventBus.getDefault().unregister(this);
        setContentView(R.layout.deliverylist);

        Const.ORDER_FLAGS = 1;// 判断新任务列表是否刷新 0-刷新；1-不刷新
        deliveryList = (MyListView) findViewById(R.id.deliverylist);
        help_deliverylist = (MyListView) findViewById(R.id.help_deliverylist);
        waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);
        ordernull = (TextView) findViewById(R.id.ordernull);

        mlocationClient = new AMapLocationClient(OrderpsActivity.this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();

        /**
         * 头部和底部刷新
         */
        mHeaderView = findViewById(R.id.mHeaderView);
        pulldown_header_text = (TextView) findViewById(R.id.pulldown_header_text);
        pulldown_header_text.setText("刷新中...");

        if (Common.isNetworkConnected(OrderpsActivity.this)) {
            // showProgressDialog("数据加载中...");
            mHeaderView.setVisibility(View.VISIBLE);
            mOrderAsyn = new OrderAsyncTask();
            mOrderAsyn.execute("sendlist");
        } else {
            closeProgressDialog();
            Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
        }

        mHandler = new Handler() {
            @SuppressWarnings("unchecked")
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS://
                        closeProgressDialog();
                        OrderSendList = new DeliveryOrderData();
                        OrderSendList = (DeliveryOrderData) msg.obj;
                        mHeaderView.setVisibility(View.GONE);

                        if (OrderSendList != null && !OrderSendList.equals("")
                                && !OrderSendList.equals("null")) {
                            psorderlist = OrderSendList.getOrderdeliverydata();
                            if ((!psorderlist.get(0)
                                    .getStatus01().equals("0") && OrderSendList
                                    .getOrderdeliverydata() != null)
                                    || (!OrderSendList.getNewhelpData().get(0)
                                    .getStatus().equals("0") && OrderSendList
                                    .getNewhelpData() != null)) {

                                if (psorderlist != null
                                        && !psorderlist
                                        .get(0).getStatus01().equals("0")) {
                                    getGpsaddr(); // 根据坐标反查地址
                                    deliveryList.setVisibility(View.VISIBLE);
                                    ordernull.setVisibility(View.GONE);
                                    deliveryadapter = new OrderDeliveryAdapter(
                                            OrderpsActivity.this,
                                            psorderlist,
                                            R.layout.deliverylist_item);
                                    deliveryList.setAdapter(deliveryadapter);

                                } else {
                                    deliveryList.setVisibility(View.GONE);
                                }
                                if (OrderSendList.getNewhelpData() != null
                                        && !OrderSendList.getNewhelpData().get(0)
                                        .getStatus().equals("0")) {
                                    help_deliverylist.setVisibility(View.VISIBLE);
                                    ordernull.setVisibility(View.GONE);
                                    helpadapter = new OrderDeliveryHelpAdapter(
                                            OrderpsActivity.this,
                                            OrderSendList.getNewhelpData(),
                                            R.layout.deliveryhelplist_item);
                                    helpadapter
                                            .setHelpOnChanged(OrderpsActivity.this);
                                    help_deliverylist.setAdapter(helpadapter);

                                } else {
                                    help_deliverylist.setVisibility(View.GONE);
                                }
                                InitLayout();
                            } else {
                                deliveryList.setVisibility(View.GONE);
                                help_deliverylist.setVisibility(View.GONE);
                                ordernull.setVisibility(View.VISIBLE);
                            }
                        } else {
                            Common.DisplayToast(OrderpsActivity.this, "暂无数据!", 1);
                        }

                        break;

                    case Const.STATE_START_QIANG://
                        closeProgressDialog();
                        qiangdan = new QiangDanData();
                        qiangdan = (QiangDanData) msg.obj;
                        Common.DisplayToast(OrderpsActivity.this,
                                qiangdan.getMessage(), 1);
                        if (qiangdan.getStatus().equals("1")) {
                            if (Common.isNetworkConnected(OrderpsActivity.this)) {
                                new OrderAsyncTask().execute("getsum");
                                // showProgressDialog("数据加载中...");
                                mHeaderView.setVisibility(View.VISIBLE);
                                mOrderAsyn = new OrderAsyncTask();
                                mOrderAsyn.execute("sendlist");
                            } else {
                                closeProgressDialog();
                                Common.DisplayToast(OrderpsActivity.this,
                                        "通信失败,请检查网络!", 1);
                            }
                        } else {
                            mHeaderView.setVisibility(View.GONE);
                        }
                        break;
                    case Const.STATE_START_LOCATION://
                        closeProgressDialog();
                        qiangdan = new QiangDanData();
                        qiangdan = (QiangDanData) msg.obj;
                        Common.DisplayToast(OrderpsActivity.this,
                                qiangdan.getMessage(), 1);
                        if (qiangdan.getStatus().equals("200")) {
                            if (Common.isNetworkConnected(OrderpsActivity.this)) {
                                new OrderAsyncTask().execute("getsum");
                                // showProgressDialog("数据加载中...");
                                mHeaderView.setVisibility(View.VISIBLE);
                                mOrderAsyn = new OrderAsyncTask();
                                mOrderAsyn.execute("sendlist");
                            } else {
                                closeProgressDialog();
                                Common.DisplayToast(OrderpsActivity.this,
                                        "通信失败,请检查网络!", 1);
                            }
                        } else {
                            mHeaderView.setVisibility(View.GONE);
                        }
                        break;
                    case Const.STATE_GETNUM_SUCC: // 获取数量成功
                        QiangDanData sumcout = (QiangDanData) msg.obj;
                        String status = sumcout.getStatus();
                        if (status != null && status.equals("1")) {
                            String xincount = sumcout.getNeworder();
                            String noget = sumcout.getNoget();
                            String nosend = sumcout.getNosend();
                            MainActivity.radio_goqh.setText("待取货(" + noget + ")");
                            MainActivity.radio_gops.setText("配送中(" + nosend + ")");
                        }
                        break;
                    case Const.STATE_GETNUM_FAIL:
                        // Common.DisplayToast(MainActivity.this, "通信失败,请检查网络!", 2);
                        break;
                    case Const.STATE_START_ERROR://
                        closeProgressDialog();
                        Common.DisplayToast(OrderpsActivity.this, "获取数据失败", 1);
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timers != null) {
            for (int i = 0; i < timers.size(); i++) {
                timers.get(timers.keyAt(i)).cancel();
            }
        }
    }

    // 根据经纬度获取地址
    private void getGpsaddr() {
        int size = psorderlist.size();
        for (int i = 0; i < size; i++) {
            try {
                OrderDeliveryData dataobj = psorderlist.get(i);
                String phoneaddr = dataobj.getOrderItemList().get(0)
                        .getPhone_addr();
                String address_road = dataobj.getAddress_road();
                if (address_road == null || address_road.equals("")
                        || address_road.equals("null")) {
                    if (phoneaddr != null && !phoneaddr.equals("")
                            && !phoneaddr.equals("null")) {
                        String[] latlng = phoneaddr.split(",");
                        double lng = Double.parseDouble(latlng[0]);
                        double lat = Double.parseDouble(latlng[1]);
                        getgpssAddress(lat, lng, dataobj, i);
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    // 初始化面板
    private void InitLayout() {
        waterfall_scroll.getView();
        waterfall_scroll.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onTop() {
                mHeaderView.setVisibility(View.VISIBLE);
                if (Common.isNetworkConnected(OrderpsActivity.this)) {
                    mOrderAsyn = new OrderAsyncTask();
                    mOrderAsyn.execute("sendlist");
                } else {
                    closeProgressDialog();
                    Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
                }
            }

            @Override
            public void onScroll() {
                // 滚动中
            }

            @Override
            public void onBottom() {
            }
        });
    }

    class OrderAsyncTask extends AsyncTask<String, String, String> {
        private QiangDanData countdata;

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("sendlist")) {// 配送中列表数据
                OrderSendList = new DeliveryOrderData();
                OrderSendList = JsonProcessHelper.jsonProcess_getSendorderList(
                        "get_rr_help_send_order_list", emp_id);
                if (OrderSendList != null) {
                    res = "state_success";
                } else {
                    res = "mi_error";
                }
            } else if (params[0].equals("send")) {// 确认收货
                qiangdan = new QiangDanData();
                qiangdan = JsonProcessHelper.jsonProcess_getQsSendFood(
                        "qs_send_food", params[1], params[2], String.valueOf(distance));
                if (qiangdan != null) {
                    res = "state_qiang";
                    EventBus.getDefault().post(new MessageEvents().setEventsType("mainshuaxin"));
                } else {
                    res = "mi_error";
                }
            } else if (params[0].equals("syg_send")) {// 随意购确认收货
                qiangdan = new QiangDanData();
                qiangdan = JsonProcessHelper.jsonProcess_getQsExSendFood(
                        "ex_send_food", params[1], params[2]);
                if (qiangdan != null) {
                    res = "state_qiang1";
                } else {
                    res = "mi_error";
                }
            } else if (params[0].equals("getsum")) { // 获取数量

                sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");
                countdata = JsonProcessHelper.jsonProcess_getOrderCount(
                        "get_order_count", uid);
                if (null != countdata) {
                    res = "get_ok";
                } else {
                    res = "ping_me_error";
                }

            }
            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("state_success")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = OrderSendList;
                mHandler.sendMessage(msg);
            } else if (result.equals("state_qiang")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_QIANG;
                msg.obj = qiangdan;
                mHandler.sendMessage(msg);
            } else if (result.equals("state_qiang1")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_LOCATION;
                msg.obj = qiangdan;
                mHandler.sendMessage(msg);
            } else if (result.equals("mi_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            } else if (result.equals("get_ok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_GETNUM_SUCC;
                msg.obj = countdata;
                mHandler.sendMessage(msg);
            } else if (result.equals("ping_me_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_GETNUM_FAIL;
                mHandler.sendMessage(msg);
            }
        }
    }

    @Override
    public void getChoiceData(String orderid, String empid, int position) {

        showProgressDialog("数据加载中...");
        if (Common.isNetworkConnected(OrderpsActivity.this)) {
            // mHeaderView.setVisibility(View.VISIBLE);
            mOrderAsyn = new OrderAsyncTask();
            mOrderAsyn.execute("send", orderid, empid);
        } else {
            closeProgressDialog();
            Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
        }

    }

    @Override
    public void getHelpChoiceData(String orderid, String empid, int position, String type) {
        showProgressDialog("数据加载中...");
        if (Common.isNetworkConnected(OrderpsActivity.this)) {
            // mHeaderView.setVisibility(View.VISIBLE);
            mOrderAsyn = new OrderAsyncTask();
            mOrderAsyn.execute("send", orderid, empid);
        } else {
            closeProgressDialog();
            Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
        }
    }

    private void countdown(final long s, final TextView tv, final boolean isTimeOut, final long s2) {
        /** 倒计时s秒，一次1秒 */
        CountDownTimer timer = new CountDownTimer(s * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                long ss;
                if (isTimeOut) {
                    ss = s2 + s - millisUntilFinished / 1000;
                } else {
                    ss = millisUntilFinished / 1000;
                }
                if (ss < 60) {
                    if (isTimeOut) {
                        tv.setText("超时" + ss + "秒");
                    } else {
                        tv.setText("剩余" + ss + "秒");
                    }
                } else if (millisUntilFinished < 3600) {
                    if (isTimeOut) {
                        tv.setText("超时" + ss / 60 + "分" + ss % 60 + "秒");
                    } else {
                        tv.setText("剩余" + ss / 60 + "分" + ss % 60 + "秒");
                    }
                } else {
                    if (isTimeOut) {
                        tv.setText("超时" + ss / 3600 + "时" + ss % 3600 / 60 + "分" + ss % 60 + "秒");
                    } else {
                        tv.setText("剩余" + ss / 3600 + "时" + ss % 3600 / 60 + "分" + ss % 60 + "秒");
                    }
                }
            }

            @Override
            public void onFinish() {
                if (isTimeOut) {
                    tv.setText("已超时");
                } else {
                    countdown(36000, tv, true, 0);
                }
            }
        }.start();

        timers.put(tv.hashCode(), timer);
    }

    public class OrderDeliveryAdapter extends CommonAdapter<OrderDeliveryData> {

        public OrderDeliveryAdapter(Context context,
                                    List<OrderDeliveryData> datas, int layoutId) {
            super(context, datas, layoutId);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void convert(ViewHolders holder, final OrderDeliveryData t, int position) {
            TextView newtaskmomey = holder.getView(R.id.delivery_money);
            TextView order_number = holder.getView(R.id.order_number);
            TextView extra_reward = holder.getView(R.id.extra_reward);
            TextView newtasktime = holder.getView(R.id.delivery_time);
            LinearLayout pslay = holder.getView(R.id.pslay);
            TextView newtask_goods_getaddress = holder.getView(R.id.delivery_goods_getaddress);
            TextView getgpsaddr = holder.getView(R.id.getgpsaddr);
            TextView orderStartTime = holder.getView(R.id.orderStartTime);
            TextView orderEndTime = holder.getView(R.id.orderEndTime);
            TextView order_end_time_stamp = holder.getView(R.id.order_end_time_stamp);
            ProgressBar progress = holder.getView(R.id.progress);

            newtaskmomey.setText("¥" + t.getReturnpay());
            order_number.setText("订单编号：" + t.getMain_id());
            extra_reward.setText(" +" + t.getExtra_reward());
            orderStartTime.setText(t.getOrder_start_time());
            orderEndTime.setText(t.getOrder_end_time());
            progress.setProgress((int) (t.getRate() * 100));

            int order_end_time_stamp1 = t.getOrder_end_time_stamp();
//            if (position == 0) {
//                order_end_time_stamp1 = 1545987600;
//            } else if (position == 1) {
//                order_end_time_stamp1 = 1545984039;
//            } else if (position == 2) {
//                order_end_time_stamp1 = 1545948039;
//            }

            if (timers == null) {
                timers = new SparseArray<>();
            }

            //获取当前时间戳
            long timeStamp = System.currentTimeMillis() / 1000;

            CountDownTimer countDownTimer = timers.get(order_end_time_stamp.hashCode());
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }

            long s1 = order_end_time_stamp1 - timeStamp;
            long s2 = timeStamp - order_end_time_stamp1;
            if (s1 > 0) {
                countdown(s1, order_end_time_stamp, false, s2);
            } else {
                if (s1 + 36000 > 0) {
                    countdown((s1 + 36000), order_end_time_stamp, true, s2);
                } else {
                    order_end_time_stamp.setText("已超时");
                }
            }

            if (!t.getAdd_time().equals("") || t.getAdd_time() != null) {
                newtasktime.setText(Common.getStrTime(t.getAdd_time()));
            }
            try {
                String address_road = t.getAddress_road();
                if (address_road == null || address_road.equals("")
                        || address_road.equals("null")) {
                    String addrss = t.getGps_addrs();
                    if (addrss != null && !addrss.equals("")) {
                        getgpsaddr.setText(addrss); // 根据经纬度反查地址
                        getgpsaddr.setVisibility(View.VISIBLE);
                    } else {
                        getgpsaddr.setVisibility(View.GONE);
                    }
                } else {
                    getgpsaddr.setText(address_road); // 根据经纬度反查地址
                    getgpsaddr.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
            }

//            newtask_goods_getaddress.setText(t.getSendaddress());
            newtask_goods_getaddress.setText(t.getOrderItemList().get(0).getUname());
            ListView ItemList = holder.getView(R.id.delivery_itemlist);
            OrderDeliveryItemAdapter itemadapter = new OrderDeliveryItemAdapter(
                    mContext, t.getOrderItemList(),
                    R.layout.deliverylist_itemlist_item, t.getMain_id(),
                    t.getSendaddress());
//			itemadapter.setOnChanged(OrderpsActivity.this);
            ItemList.setAdapter(itemadapter);
            itemadapter.setOnClickSendFinishListener(new OrderDeliveryItemAdapter.OnClickSendFinishListener() {
                @Override
                public void onClickSendFinishListener(View view, int position) {
//                    if (t.getStatus().equals("7")) {//判断与卖家距离小于200米
                        buyerLat = t.getOrderItemList().get(position).getLat();
                        buyerLnt = t.getOrderItemList().get(position).getLng();
                        LatLng lng1 = new LatLng(lat, lnt);
                        LatLng lng2 = new LatLng(buyerLat, buyerLnt);
                        distance = AMapUtils.calculateLineDistance(lng1, lng2);
//                        if (distance < 200) {
                            SharedPreferences sp = mContext.getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                            String empid = sp.getString("uid", "");
                            if (!empid.equals("") && empid != null) {
                                showProgressDialog("数据加载中...");
                                if (Common.isNetworkConnected(OrderpsActivity.this)) {
                                    // mHeaderView.setVisibility(View.VISIBLE);
                                    mOrderAsyn = new OrderAsyncTask();
                                    mOrderAsyn.execute("send", t.getOrderItemList().get(position).getOrder_id(), empid);
                                } else {
                                    closeProgressDialog();
                                    Common.DisplayToast(OrderpsActivity.this, "通信失败,请检查网络!", 1);
                                }
                            }
//                        } else {
//                            Toast.makeText(mContext, "您当前位置距离顾客较远，无法点击送达。", Toast.LENGTH_SHORT).show();
//                        }
//                    }
                }
            });
            pslay.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (t.getMain_id() != null && !t.getMain_id().equals("")) {
                        Intent intent = new Intent(mContext,
                                OrderDetailNewActivity.class);
                        intent.putExtra("mainid", t.getMain_id());
                        intent.putExtra("status", "ps");
                        mContext.startActivity(intent);
                    }
                }
            });
            TextView lianxiguke = holder.getView(R.id.lianxiguke);
            TextView laixishangjia = holder.getView(R.id.laixishangjia);
            TextView ditudaohang = holder.getView(R.id.ditudaohang);
            lianxiguke.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    callPhoneNumber(t.getOrderItemList().get(0).getPhone());
                }
            });
            laixishangjia.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    callPhoneNumber(t.getSite_phone());
                }
            });
            ditudaohang.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Addressclick(t.getOrderItemList().get(0).getLat()+"",t.getOrderItemList().get(0).getLng()+"");
                }
            });
        }

    }
    private void Addressclick(String lat,String lng) {
        if (!lat.equals("0.0") && null != lat && !lng.equals("0.0") && null != lng && !lat.equals("null") && !lng.equals("null")) {
            Intent intent = new Intent(this, MyMapLocation.class);
            intent.putExtra("lat", lat);
            intent.putExtra("lng", lng);
            this.startActivity(intent);
        } else {
            Common.DisplayToast(this, "坐标获取失败！", 2);
        }
    }
    public void callPhoneNumber(String phoneNumber) {
        if (phoneNumber != null && !phoneNumber.equals("")) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(this.getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    }
    // 反查的
    void getgpssAddress(double lat, double lng,
                        final OrderDeliveryData dataobj, final int i) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(this);
        geocoderSearch
                .setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
                    @Override
                    public void onGeocodeSearched(GeocodeResult result,
                                                  int rCode) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onRegeocodeSearched(RegeocodeResult result,
                                                    int rCode) {
                        if (rCode == 1000) {
                            String formatAddress = result.getRegeocodeAddress()
                                    .getFormatAddress();
                            try {
                                dataobj.setGps_addrs(formatAddress);
                                psorderlist.set(i, dataobj);
                                OrderSendList.setOrderdeliverydata(psorderlist);
                                if (deliveryadapter != null) {
                                    deliveryadapter.notifyDataSetChanged();
                                }

                            } catch (Exception e) {
                            }
                        }
                    }
                });
        LatLonPoint lp = new LatLonPoint(lat, lng);
        RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        emp_id = sp.getString("uid", "");
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0
                    && Common.isNetworkConnected(OrderpsActivity.this)) {
                // 定位成功回调信息，设置相关消息
                // amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                lat = amapLocation.getLatitude();// 获取纬度
                lnt = amapLocation.getLongitude();// 获取经度
//                amapLocation.getAccuracy();// 获取精度信息
//                if (amapLocation.getLatitude() > 0
//                        && amapLocation.getLongitude() > 0) {


//                }
            } else {
                Common.DisplayToast(OrderpsActivity.this, "定位失败,请检查网络!" + amapLocation.getErrorCode(), 1);
            }
        }
    }

    @Override
    public void zhuandan(String mainid, String empid, int position) {

    }
}
